import Actions from './actions';
import DB from '../../app/db';
import {Toast} from 'saltui';
import {fromJS, OrderedMap} from 'immutable';
import JdjlHelp from './../utils';
import Reflux from 'reflux';
import nattyStorage from 'natty-storage';
import moment from "moment/moment";

const storage = nattyStorage({
  type: 'localStorage',  // 缓存方式, 默认为'localStorage'
  key: 'sskj-dingtalk-jdjl',     // !!! 唯一必选的参数, 用于内部存储 !!!
});

const storageUser = nattyStorage({
  type: 'localStorage',  // 缓存方式, 默认为'localStorage'
  key: 'sskj-dingtalk-user',     // !!! 唯一必选的参数, 用于内部存储 !!!
});

module.exports = Reflux.createStore({
  listenables: [Actions],
  data: {
    //数据主键ID
    spId: '',
    //是否锁定
    readOnly: false,
    //责任主体
    zrzt: [],
    xxjda:[],
    jdry:[],
    //操作类型
    operType: '',
    //是否上传
    isUpload: false,
    //监督检查记录
    zgtzs: OrderedMap(),
    jlrq:new Date().getTime(),
    zgqx:new Date().getTime(),
    //形象进度
    xxjd: [],
    //当前用户
    user: fromJS(storageUser),
  },

  //上传纪录
  onUpZgtzs: function (params, cb) {
    let t = this;
    JdjlHelp.showTost('loading', '上传中...', false, true);
    moment().format();
    t.data.zgtzs = t.data.zgtzs.set('jlrq', moment(t.data.jlrq).format('YYYY-MM-DD HH:mm:ss'));
    t.data.zgtzs = t.data.zgtzs.set('zgqx', moment(t.data.zgqx).format('YYYY-MM-DD HH:mm:ss'));
    DB.aqzgtzs.up({id: t.data.zgtzs.get('id')}).then(
      function (content) {
        console.log(content);
        if (content.success) {
          Toast.show({
            type: 'success',
            content: '上传成功!',
            autoHide: true,
            hasMask: true,
            onDidHide: function () {
              if (t.data.spId == 'new') {
                storage.remove('aqzgtzs');
              }
              cb(params);
            }
          });

        } else {
          JdjlHelp.showTost('success', '上传失败!', true, false);
        }
      },
      function (error) {
        alert('错误提示: ' + error.message);
      });
  },

  //删除记录
  onDelZgtzs: function (params, cb) {
    let t = this;
    JdjlHelp.showTost('loading', '删除中...', false, true);
    DB.aqzgtzs.del({id: t.data.zgtzs.get('id')}).then(
      function (content) {
        console.log(content);
        if (content.success) {
          Toast.show({
            type: 'success',
            content: '删除成功!',
            autoHide: true,
            hasMask: true,
            onDidHide: function () {
              cb(params);
            }
          });
        } else {
          JdjlHelp.showTost('success', '删除失败!', true, false);
        }
      },
      function (error) {
        alert('错误提示: ' + error.message);

      });
  },

  //保存质量检查记录
  onSaveZgtzs: function (params, cb) {
    let t = this;
    if(JdjlHelp.jdryCheck(t.data.jdry,t.data.user.get('name')))
    {
      JdjlHelp.showTost('loading', '提交中...', false, true);
      moment().format();
      t.data.zgtzs = t.data.zgtzs.set('jlrq', moment(t.data.jlrq).format('YYYY-MM-DD HH:mm:ss'));
      t.data.zgtzs = t.data.zgtzs.set('zgqx', moment(t.data.zgqx).format('YYYY-MM-DD HH:mm:ss'));
      DB.aqzgtzs.save(t.data.zgtzs.toJS()).then(
        function (content) {
          if (content.success) {
            Toast.show({
              type: 'success',
              content: '提交成功!',
              autoHide: true,
              hasMask: true,
              onDidHide: function () {
                if (t.data.spId == 'new') {
                  storage.remove('zgtzs');
                }

                cb(params);
              }
            });
          } else {
            JdjlHelp.showTost('success', '提交失败!', true, false);
          }
        },
        function (error) {
          alert('错误提示: ' + error.message);
        });
    }else {
      Toast.show({
        type: 'error',
        content: '非小组人员!',
        onHide: function () {
        }
      });
    }

  },

  //选择形象进度
  onSelectXxjd: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.xxjdChange(t.data.zgtzs, params);
    t.updateComponent();
  },

  //形象进度描述
  onSelectXxjdms: function (params) {
    let t = this;
    t.data.zgtzs = t.data.zgtzs.set('xxjdms', params);
    t.updateComponent();
  },

  //选择形象进度
  onSelectXxjdA: function (params) {
    let t = this;
    t.data.xxjda = params;
    t.data.zgtzs = t.data.zgtzs.set('xxjd', params.text);
    t.updateComponent();
  },

  //选择责任主体
  onZrztNameChange(obj,params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.zrztNameSelect(t.data.zgtzs,t.data.zrzt ,params,obj);
    t.updateComponent();
  },

  //选择工程
  onSelectEng: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.engSelect(t.data.zgtzs, params);
/*    t.data.zrzt = JdjlHelp.getZrzt(t.data.zgtzs);
    t.data.zgtzs = t.data.zgtzs.set('cjjgs', fromJS(t.data.zrzt));*/
    t.data.zrzt = JdjlHelp.getZrzt(t.data.zgtzs,t);
    t.data.jdry = JdjlHelp.getJdry(t.data.zgtzs,t,'安全');
    t.data.zgtzs = t.data.zgtzs.set('cjjgs', fromJS(t.data.zrzt));
    t.data.zgtzs = t.data.zgtzs.set('jdrys', fromJS(t.data.jdry));
    t.updateComponent();
  },

  onSelectZrzt: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.zrztSelect(t.data.zgtzs, t.data.zrzt, params);
    t.updateComponent();
  },

  //选择问题类型
  onSelectWtlx: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.wtlxSelectForLX(t.data.zgtzs, params,aqlxdata);
    t.updateComponent();
  },

  //添加问题描述
  onChangeWtms: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.wtmsChange(t.data.zgtzs, params);
    t.updateComponent();
  },

  //添加问题
  onAddWt: function () {
    let t = this;
    t.data.zgtzs = JdjlHelp.wtAqAdd(t.data.zgtzs);
    t.updateComponent();
  },

  //删除问题
  onDelWt: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.wtDel(t.data.zgtzs, params);
    t.updateComponent();
  },


  //删除附件
  onDelFile: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.fileDel(t.data.zgtzs, params);
    t.updateComponent();
  },

  //选择整改期限
  onSelectZgqx: function (params) {
    let t = this;
    /*t.data.zgtzs = t.data.zgtzs.set('zgqx', params.zgqx);*/
    t.data.zgqx = params.zgqx;
    t.updateComponent();
  },

  //选择记录日期
  onSelectJlrq: function (params) {
    let t = this;
    /*t.data.zgtzs = t.data.zgtzs.set('jlrq', params.jlrq);*/
    t.data.jlrq = params.jlrq;
    t.updateComponent();
  },

  //添加附件
  onAddFile: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.fileAdd(t.data.zgtzs, params);
    t.updateComponent();
  },

  //添加上传图片
  onAddImage: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.imageAdd(t.data.zgtzs, params);
    t.updateComponent();
  },


  //删除图片
  onDelImage: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.imageDel(t.data.zgtzs, params);
    t.updateComponent();
  },

  //地图定位
  onSelectMap: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.mapEdit(t.data.zgtzs, params);
    t.updateComponent();
  },

  //删除监督人员
  onDelJdry: function (params) {
    let t = this;
    if (t.data.zgtzs.get('jdrys').get(params).get('name') != t.data.user.get('name')) {
      t.data.zgtzs = JdjlHelp.jdryDel(t.data.zgtzs, params);
      t.updateComponent();
    }
  },

  //添加监督人员
  onAddJdry: function (params) {
    let t = this;
    t.data.zgtzs = JdjlHelp.jdryAdd(t.data.zgtzs, params);
    t.updateComponent();
  },

  onChangeNote: function (params) {
    let t = this;
    t.data.zgtzs = t.data.zgtzs.set('note', params);
    t.updateComponent();
  },

  //操作记录
  onOperZgtzs: function (params) {
    let t = this;
    storage.remove('zgtzs');
    t.data.operType = params.operType;
    t.data.spId = params.spId;
    if (t.data.operType == 'add') {
      t.newZgtzs();
    }
    if (t.data.operType == 'edit') {
      t.editZgtzs();
    }
    if (t.data.operType == 'select') {
      t.onSelectEng(params.eng);
    }


    dd.device.notification.hidePreloader({
      onSuccess: function (result) {
        /*{}*/
      },
      onFail: function (err) {
      }
    });
  },

  onReflushZgtzs: function () {
    let t = this;
    t.data.zrzt = [];
    t.data.xxjd = require('./../../contas/contas.js').xxjd;
    t.data.xxjd.map((v, k)=> {
      v.checked = false;
    });
    t.data.zgtzs = fromJS({
      id: '',
      //编码
      coding: '',
      //记录类型名称
      jllxName: '安全问题整改通知书',
      //记录类型CODE
      jllx: '0022',
      //路由
      router: 'aqzgtzsedit',
      //记录日期
      jlrq: new Date().getTime(),
      //整改期限
      zgqx: '',
      //监督工程
      eng: {},
      //监督人员
      jdrys: [],
      //地图
      map: {},
      //发现问题
      wt: [],
      //形象进度
      xxjdms: '',
      xxjd:'',
      //责任主体
      cjjgs: [],
      //描述
      note: '',
      //创建者编码
      creatorId: '',
    });

    //如果缓存有用户信息就使用用户信息
    if (t.data.user.get('userid')) {
      t.data.zgtzs = t.data.zgtzs.set('jdrys', t.data.zgtzs.get('jdrys').push(fromJS({
        emplId: storageUser.get('userid'),
        avatar: storageUser.get('avatar'),
        name: storageUser.get('name')
      })));

      t.data.zgtzs = t.data.zgtzs.set('creatorId', storageUser.get('userid'));
    }
  },

  //新增记录
  newZgtzs: function () {
    let t = this;
    t.data.readOnly = false;
    if (storage.has('zgtzs').has) {
      t.data.zgtzs = fromJS(storage.get('zgtzs'));
      t.data.xxjd = JdjlHelp.initXxjd(t.data.zgtzs, require('./../../contas/contas.js').xxjd);
      t.data.zrzt = JdjlHelp.initZrzt(t.data.zgtzs, t.data.zrzt, t.data.readOnly);

    } else {
      this.onReflushZgtzs();
    }


    t.updateComponent();

  },


  //编辑监督记录
  editZgtzs: function () {
    let t = this;
    DB.aqzgtzs.get({spId: t.data.spId}).then(
      function (content) {
        console.log(content);
        t.data.readOnly = content.isUpload;
        t.data.zgtzs = fromJS(content);

        //记录日期时间兼容问题IOS和ANDROID
        var jlrq = new Date(JdjlHelp.getDateDiff(content.jlrq)).getTime();
        t.data.zgtzs = t.data.zgtzs.set('jlrq', jlrq);
        t.data.jlrq = content.jlrq;
        var zgqx = new Date(JdjlHelp.getDateDiff(content.zgqx)).getTime();
        t.data.zgtzs = t.data.zgtzs.set('zgqx', zgqx);
        t.data.zgqx = content.zgqx;
        t.data.xxjd = JdjlHelp.initXxjd(t.data.zgtzs, require('./../../contas/contas.js').xxjd);
        t.data.zrzt = JdjlHelp.initZrzt(t.data.zgtzs, t.data.zrzt, t.data.readOnly);


        t.updateComponent();

      },
      function (error) {
        Toast.hide(function () {
          alert('error: ' + JSON.stringify(error));
        });
      });

  },

  updateComponent: function () {
    let t = this;
    JdjlHelp.saveLocalStorage(t.data.operType, 'zgtzs', t.data.zgtzs, storage);
    this.trigger(t.data);
  },

  getInitialState: function () {
    let t = this;
    return t.data;
  },


});
